package com.luke.zk;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * @Descrtption CuratorCreate
 * @Author luke
 * @Date 2020/5/22
 **/
public class CuratorCreate {

    private String IP = "192.168.0.17:2181";

    private CuratorFramework client;

    @Before
    public void before(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000,3);
        client = CuratorFrameworkFactory.builder()
                .connectString(IP)//地址端口
                .sessionTimeoutMs(5000)//会话超时
                .retryPolicy(retryPolicy)//重连机制
                .namespace("create")//命名空间
                .build();
        client.start();
    }

    @After
    public void after(){
        client.close();
    }

    @Test
    public void create1() throws Exception{
        client.create().withMode(CreateMode.PERSISTENT)
                .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)
                .forPath("/node2","node2".getBytes());
        System.out.println("创建完成");
    }

    @Test
    public void create2() throws Exception{
        client.create().forPath("/node3","node3".getBytes()); //持久化非有序节点
    }

    @Test
    public void create3() throws Exception{
        //临时节点，值为ip地址
        String path = client.create().withMode(CreateMode.EPHEMERAL).forPath("/temp");
        System.out.println(path);
        System.in.read();
    }

}
